package cn.wolfcode.luowowo.wesite.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.wesite.annotation.RequireLogin;
import cn.wolfcode.luowowo.wesite.until.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by LENOVO on 2019/8/9.
 */
//登录控制器
public class CheckLoginInterceptor implements HandlerInterceptor{
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查用户是否登录
        //获取当前请求的方法 springmvc启动的时候会将所有映射方法封装成HandlerMethod对象
        if(handler instanceof HandlerMethod){//判断是否是动态请求
            HandlerMethod hm=(HandlerMethod)handler;//强转只有动态请求才可以强转
            //判断该方法上是否贴有RequireLogin 注解
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                    //贴有标签的才会进行登录判断
                String token = CookieUtil.getToken(request);
                UserInfo userInfo = userInfoRedisService.getUserByToken(token);
                if (userInfo==null){
                    response.sendRedirect("/login.html");
                    return false;

                }
            }
        }
        //如果沒貼直接放行
        return true;
    }
}
